﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Data;
using System.Data.SqlClient;
using SistemaAcademicoBO;

namespace SistemaAcademicoDAL
{
    public class ProcedureCall
    {
        private List<ProcedureParam> parameters;
        private SqlConnection connection;
        private SqlCommand command;
        private SqlDataReader dataReader;
        private String procedureName;

        public List<ProcedureParam> Parameters
        {
            get { return parameters; }
            set { parameters = value; }
        }

        public ProcedureCall(String procedureName, SqlConnection connection)
        {
            parameters = new List<ProcedureParam>();

            this.procedureName = procedureName;
            this.connection = connection;
        }

        public void Execute(bool retrieveResultSet)
        {
            command = new SqlCommand();

            command.Connection = connection;
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = procedureName;

            command.Parameters.Clear();

            foreach (ProcedureParam param in parameters)
            {
                SqlParameter parameter = new SqlParameter();

                parameter.ParameterName = param.Name;
                parameter.SqlDbType = param.Type;
                parameter.Size = param.Size;
                parameter.Direction = ParameterDirection.Input;
                parameter.Value = param.Value;

                command.Parameters.Add(parameter);
            }

            if (retrieveResultSet)
                dataReader = command.ExecuteReader();
            else
                command.ExecuteNonQuery();
        }

        public List<IEntity> ExtractFromResultSet(Type objectType)
        {
            List<IEntity> returnList = new List<IEntity>();
            PropertyInfo[] info = objectType.GetProperties(BindingFlags.Instance | BindingFlags.Public);

            Object listItem;

            while (dataReader.Read())
            {
                listItem = Activator.CreateInstance(objectType);

                foreach (PropertyInfo propertyInfo in info)
                {
                    if (dataReader[propertyInfo.Name] is DBNull)
                        propertyInfo.SetValue(listItem, null, null);
                    else
                        propertyInfo.SetValue(listItem, dataReader[propertyInfo.Name], null);
                }

                returnList.Add((IEntity)listItem);
            }

            dataReader.Close();

            return returnList;
        }

        public bool ExistsResultSet()
        {

            if (dataReader == null)
                return false;

            return dataReader.HasRows;
        }
    }
}
